package com.lfk.three.con;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;

import com.lfk.three.item.NetItem;
import com.lfk.three.static_info.static_info;
import com.lfk.three.utils.logger.Logger;
import com.zhy.http.okhttp.callback.Callback;

import java.util.HashMap;

/**
 * Created by liufengkai on 16/4/9.
 */
public class NetWorkQueue {
    private HashMap<String, Callback> callbackMap;

    private static NetWorkQueue queue = null;

    public NetWorkQueue() {
        callbackMap = new HashMap<>();
    }

    public static NetWorkQueue getInstance() {
        if (queue == null) {
            synchronized (NetWorkQueue.class) {
                if (queue == null) {
                    queue = new NetWorkQueue();
                }
            }
        }
        return queue;
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case static_info.POST_DATA_NO_PARAMS:
                    postWithoutParams(msg);
                    break;

                case static_info.POST_DATA:
                    postWithParams(msg);
                    break;
            }
        }
    };

    private void postWithParams(Message msg) {
        NetItem item = (NetItem) msg.obj;
        NetWorkHandler.Post(item.url, callbackMap.get(item.callback_name), item.params);
    }

    private void postWithoutParams(Message msg) {
        NetItem no_item = (NetItem) msg.obj;
        Logger.e(no_item.url);
        NetWorkHandler.Post(no_item.url, callbackMap.get(no_item.callback_name));
    }

    public void addCallBack(String name, Callback callback) {
        callbackMap.put(name, callback);
    }

    public void sendMessage(int flag, NetItem item) {
        Message msg = handler.obtainMessage();
        msg.what = flag;
        msg.obj = item;
        handler.sendMessage(msg);
    }
}
